﻿using Microsoft.AspNetCore.Mvc;
using Quartz;
using Quartz.Spi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WXApi.Model;
using WxTenpay.Common;
using WxTenpay.Jobs;
using WxTenpay.Service;
using WxTenpay.Service.Model;

namespace WXApi.Controllers.Job
{
    /// <summary>
    /// 获取菜单信息类
    /// </summary>
    [Route("[controller]/[action]")]
    [ApiController]
    [Action]
    public class JobController : ReqDataControllerBase
    {

        private readonly ISchedulerFactory _schedulerFactory;
        private readonly IJobFactory _jobFactory;
        private IJobTask _jobtask;
        private IJobTaskRecord _jobtaskrecord;
        private readonly ISysLog _syslog;
        public JobController(ISchedulerFactory schedulerFactory, IJobFactory jobFactory, IJobTask jobtask, IJobTaskRecord jobtaskrecord, ISysLog syslog)
        {
            this._jobFactory = jobFactory;
            this._schedulerFactory = schedulerFactory;
            this._jobtask = jobtask;
            this._jobtaskrecord = jobtaskrecord;
            this._syslog = syslog;
        }



        /// <summary>
        /// 获取所有的作业
        /// </summary>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult GetJobs([FromBody] PageModel.PageParm parm)
        {

            try
            {
                var data = _jobtask.GetPages(parm);
                return Success(data);
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = _syslog;
                model.logmodel = new SysLogEntity { Action = "Job/GetJobs", Content = ex.ToString(), Name = "JOB任务，获取所有的作业" };
                return ErrorLog(model);
            }


        }
        /// <summary>
        /// 获取作业运行日志
        /// </summary>
        /// <param name="taskName"></param>
        /// <param name="groupName"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public ActionResult GetRunLog([FromBody] PageModel.PageParm parm)
        {
            try
            {
                if (parm.data.IsEmpty())
                    return Error("参数错误！");

                var guid = parm.data.ToString();
                var data = _jobtaskrecord.GetPages(parm, x => x.JobTaskGuId == guid, x => x.Id, 2);
                return Success(data);
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = _syslog;
                model.logmodel = new SysLogEntity { Action = "Job/GetRunLog", Content = ex.ToString(), Name = "JOB任务，获取作业运行日志" };
                return ErrorLog(model);
            }

        }
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<IActionResult> Add([FromBody] JobTaskEntity taskOptions)
        {

            try
            {
                if (_jobtask.GetModel(x => x.GroupName == taskOptions.GroupName && x.TaskName == taskOptions.TaskName) != null)
                    return Error("对不起，添加失败，信息已存在！");

                taskOptions.Create();
                _jobtask.Add(taskOptions);

                return Success(await taskOptions.AddJob(_schedulerFactory, jobFactory: _jobFactory));
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = _syslog;
                model.logmodel = new SysLogEntity { Action = "Job/Add", Content = ex.ToString(), Name = "JOB任务，添加任务" };
                return ErrorLog(model);
            }


        }
        /// <summary>
        /// 移除任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<IActionResult> Remove([FromBody] JobTaskEntity taskOptions)
        {

            try
            {

                var model = _jobtask.GetModel(x => x.GuId == taskOptions.GuId);
                if (model == null)
                    return Error("参数错误！");

                model.Status = 5;
                _jobtask.Update(model);
                return Success(await _schedulerFactory.Remove(model));

            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = _syslog;
                model.logmodel = new SysLogEntity { Action = "Job/Remove", Content = ex.ToString(), Name = "JOB任务，移除任务" };
                return ErrorLog(model);
            }

        }
        /// <summary>
        /// 修改任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<IActionResult> Update([FromBody] JobTaskEntity taskOptions)
        {
            try
            {
                var model = _jobtask.GetModel(x => x.GuId == taskOptions.GuId);
                if (model == null)
                    return Error("参数错误！");

                model.ApiUrl = taskOptions.ApiUrl;
                model.AuthKey = taskOptions.AuthKey;
                model.AuthValue = taskOptions.AuthValue;
                model.Describe = taskOptions.Describe;
                model.GroupName = taskOptions.GroupName;
                model.Interval = taskOptions.Interval;
                model.RequestType = taskOptions.RequestType;
                model.TaskName = taskOptions.TaskName;
                _jobtask.Update(model);
                return Success(await _schedulerFactory.Update(taskOptions));
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = _syslog;
                model.logmodel = new SysLogEntity { Action = "Job/Update", Content = ex.ToString(), Name = "JOB任务，修改任务" };
                return ErrorLog(model);
            }



        }
        /// <summary>
        /// /暂停
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<IActionResult> Pause([FromBody] JobTaskEntity taskOptions)
        {
            try
            {
                var model = _jobtask.GetModel(x => x.GuId == taskOptions.GuId);
                if (model == null)
                    return Error("参数错误！");

                model.Status = 5;
                _jobtask.Update(model);
                return Success(await _schedulerFactory.Pause(model));
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = _syslog;
                model.logmodel = new SysLogEntity { Action = "Job/Pause", Content = ex.ToString(), Name = "JOB任务，暂停" };
                return ErrorLog(model);
            }

        }
        /// <summary>
        /// 开始任务
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<IActionResult> Start([FromBody] JobTaskEntity taskOptions)
        {

            try
            {
                var model = _jobtask.GetModel(x => x.GuId == taskOptions.GuId);
                if (model == null)
                    return Error("参数错误！");

                model.Status =0;
                _jobtask.Update(model);
                return Success(await _schedulerFactory.Start(model));

            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = _syslog;
                model.logmodel = new SysLogEntity { Action = "Job/Start", Content = ex.ToString(), Name = "JOB任务，开始任务" };
                return ErrorLog(model);
            }

        }
        /// <summary>
        /// /立即执行
        /// </summary>
        /// <param name="taskOptions"></param>
        /// <returns></returns>
        /// 
        [HttpPost]
        public async Task<IActionResult> Run([FromBody] JobTaskEntity taskOptions)
        {
            try
            {

                var model = _jobtask.GetModel(x => x.GuId == taskOptions.GuId);
                if (model == null)
                    return Error("参数错误！");
                return Success(await _schedulerFactory.Run(model));
            }
            catch (Exception ex)
            {
                ErrorLogDto model = new ErrorLogDto();
                model.data = "系统错误！";
                model._syslog = _syslog;
                model.logmodel = new SysLogEntity { Action = "Job/Run", Content = ex.ToString(), Name = "JOB任务，立即执行" };
                return ErrorLog(model);
            }

        }


    }
}
